import Vue from "vue";

import messageBox from "./message-box.vue";

const messageBoxConstructor = Vue.extend(messageBox);

let instance;
const initInstance = () => {
  instance = new messageBoxConstructor({
    el: document.createElement("div")
  });
};
const defaults = {
  title: "提示",
  visible: false,
  message: "确定执行操作",
  showConfirmButton: true,
  showCancelButton: true,
  confirmButtonText: "确定",
  cancelButtonText: "取消",
  confirmButtonClass: "",
  cancelButtonClass: "",
  confirmButtonHighlight: false,
  cancelButtonHighlight: false,
  showIcon: false,
  renderContent: null
};
const setDefaults = () => {
  setTimeout(() => {
    for (let k in defaults) {
      if (defaults.hasOwnProperty(k)) {
        instance[k] = defaults[k];
      }
    }
  }, 200);
};

const MessageBox = function(options) {
  if (Vue.prototype.$isServer) return;
  if (!instance) {
    initInstance();
  }
  instance.setDefaults = setDefaults;
  instance.visible = true;
  for (let k in options) {
    if (options.hasOwnProperty(k)) {
      instance[k] = options[k];
    }
  }
  document.body.appendChild(instance.$el);
  return new Promise((resolve, reject) => {
    instance.callback = (vm, type) => {
      vm.visible = false;
      vm.setDefaults();
      if (type === "cancel") {
        reject(type);
      }
      resolve(type);
    };
  });
};
MessageBox.$name = "$messageBox";
export default MessageBox;
